package org.oneboot.core.mvc;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.oneboot.core.cache.local.DictionaryService;
import org.oneboot.core.cache.local.UploadWarpVoEvent;
import org.oneboot.core.cache.local.WarpTheVoService;
import org.oneboot.core.enums.EnumObject;
import org.oneboot.core.exception.CommonErrorCode;
import org.oneboot.core.exception.ObootException;
import org.oneboot.core.mvc.base.AuthUser;
import org.oneboot.core.mybatis.base.BaseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 
 * @author shiqiao.pro
 * 
 */
public class BaseController extends ObootBaseController {

	@Autowired(required = false)
	protected DictionaryService dictionaryService;
	@Autowired(required = false)
	protected WarpTheVoService warpTheVoService;

	protected void updateWarpVO(String key) {
		applicationContext.publishEvent(new UploadWarpVoEvent(key));
	}

	protected void publishEvent(ApplicationEvent event) {
		applicationContext.publishEvent(event);
	}

	protected String getWarpNameByDict(String fieldValue, String type) {
		if (dictionaryService != null) {
			return dictionaryService.getNameByTypeCode(type, fieldValue);
		} else {
			return fieldValue;
		}
	}

	protected String getWarpName(String fieldValue, String cacheName) {
		Map<String, EnumObject> cacheAllMap = warpTheVoService.getMap(cacheName);
		EnumObject eo = cacheAllMap.get(fieldValue);
		if (eo != null) {
			return eo.getName();
		}
		return fieldValue;
	}

	protected String getWarpNameSplit(String fieldValue, String cacheName) {
		return getWarpNameSplit(fieldValue, cacheName, ",");
	}

	protected String getWarpNameSplit(String fieldValue, String cacheName, String regex) {
		List<String> nameList = new ArrayList<>();
		if (StringUtils.isNotBlank(fieldValue)) {
			List<String> vList = Arrays.asList(fieldValue.split(regex));
			for (String v : vList) {
				nameList.add(getWarpName(v, cacheName));
			}
		}

		return StringUtils.join(nameList, ",");
	}

	protected String getUserId() {
		try {
			return getUserDetails().getUserId();
		} catch (Exception e) {
			return null;
		}
	}

	protected AuthUser getUserDetails() {
		try {
			AuthUser userDetails = (AuthUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
			return userDetails;
		} catch (Exception e) {
			throw new ObootException(CommonErrorCode.SESSION_EXPIRATION, 1);
		}
	}

	/**
	 * 设置新建者信息
	 * 
	 * @param base
	 */
	protected void setCreateInfo(BaseModel base) {
		base.setCreator(getUserId());
		base.setUpdater(getUserId());
	}

	/**
	 * 设置新建信息
	 * 
	 * @param base
	 */
	protected void setModifyInfo(BaseModel base) {
		base.setUpdater(getUserId());
	}
}
